
const myAjax = ({ method = "GET", url }) => {
	return new Promise((resolve, reject) => {
		const xhr = new XMLHttpRequest()
		xhr.open(method, url)
		xhr.send()
		xhr.responseType = "json"
		xhr.onreadystatechange = function() {
			if(xhr.readyState === 4) {
				if(xhr.status === 200) {
					resolve(xhr.response)
				} else {
					reject(xhr.statusText)
				}
			}
		}
	})
}


/*
async 会返回Promise对象，
一旦遇到await就会等待await函数执行完成后在执行之后的代码

await 后的函数一定是Promise函数
*/


function timeoutP(ms) {
	return new Promise((resolve, reject) => {
		setTimeout(function() {
			resolve("异步操作完成")
		}, ms)
	})
}

// async function asyncFun() {
const asyncFun = async () => {
	// timeoutP(3000).then(res => {
	// 	console.log(res)
	// })
	
	// 第一种获取await后Promise返回值
	// await timeoutP(1000).then(res => {
	// 	console.log(res)
	// })
	// 第一种获取await后Promise返回值
	const result = await timeoutP(3000)
	// const result = await Promise.reject("error")
	// console.log(result)
	// reject
	// throw new Error("asyncFun error")
	console.log("==============")
	// resove
	// return 123
	return result
}

asyncFun().then((res) => {
	console.log(res)
}).catch(err => {
	console.log(err)
})


/*
(async function() {
	try {
		await asyncFun()
	} catch (e) {
		console.log(err)
	}
})()
*/

/*
timeoutP(3000).then(res => {
	console.log(res)
})*/










